home *** CD-ROM | disk | FTP | other *** search
/ PC World 2008 February (DVD) / PCWorld_2008-02_DVD.iso / v cisle / PHP / PHP.exe / EasyPHP-2.0b1-setup.exe / {app} / phpmyadmin / sql.php < prev    next >
Encoding:
PHP Script  |  2006-11-18  |  34.1 KB  |  861 lines

  1. <?php
  2. /* $Id: sql.php 9706 2006-11-17 08:49:25Z nijel $ */
  3. // vim: expandtab sw=4 ts=4 sts=4:
  4. /**
  5.  * @todo    we must handle the case if sql.php is called directly with a query
  6.  *          what returns 0 rows - to prevent cyclic redirects or includes
  7.  */
  8.  
  9. /**
  10.  * Gets some core libraries
  11.  */
  12. require_once './libraries/common.lib.php';
  13. require_once './libraries/Table.class.php';
  14. require_once './libraries/tbl_indexes.lib.php';
  15. require_once './libraries/check_user_privileges.lib.php';
  16. require_once './libraries/bookmark.lib.php';
  17.  
  18. /**
  19.  * Could be coming from a subform ("T" column expander)
  20.  */
  21. if (isset($_REQUEST['dontlimitchars'])) {
  22.     $dontlimitchars = $_REQUEST['dontlimitchars'];
  23. }
  24.  
  25. /**
  26.  * Defines the url to return to in case of error in a sql statement
  27.  */
  28. // Security checkings
  29. if (!empty($goto)) {
  30.     $is_gotofile     = preg_replace('@^([^?]+).*$@s', '\\1', $goto);
  31.     if (!@file_exists('./' . $is_gotofile)) {
  32.         unset($goto);
  33.     } else {
  34.         $is_gotofile = ($is_gotofile == $goto);
  35.     }
  36. } // end if (security checkings)
  37.  
  38. if (empty($goto)) {
  39.     $goto = (! isset($table) || ! strlen($table)) ? $cfg['DefaultTabDatabase'] : $cfg['DefaultTabTable'];
  40.     $is_gotofile  = true;
  41. } // end if
  42. if (!isset($err_url)) {
  43.     $err_url = (!empty($back) ? $back : $goto)
  44.              . '?' . PMA_generate_common_url(isset($db) ? $db : '')
  45.              . ((strpos(' ' . $goto, 'db_details') != 1 && isset($table)) ? '&table=' . urlencode($table) : '');
  46. } // end if
  47.  
  48. // Coming from a bookmark dialog
  49. if (isset($fields['query'])) {
  50.     $sql_query = $fields['query'];
  51. }
  52.  
  53. // This one is just to fill $db
  54. if (isset($fields['dbase'])) {
  55.     $db = $fields['dbase'];
  56. }
  57.  
  58. // Default to browse if no query set an we have table
  59. // (needed for browsing from DefaultTabTable)
  60. if (! isset($sql_query) && isset($table) && isset($db)) {
  61.     require_once './libraries/bookmark.lib.php';
  62.     $book_sql_query = PMA_queryBookmarks($db,
  63.         $GLOBALS['cfg']['Bookmark'], '\'' . PMA_sqlAddslashes($table) . '\'',
  64.         'label');
  65.  
  66.     if (! empty($book_sql_query)) {
  67.         $sql_query = $book_sql_query;
  68.     } else {
  69.         $sql_query = 'SELECT * FROM ' . PMA_backquote($table);
  70.     }
  71.     unset($book_sql_query);
  72.  
  73.     // set $goto to what will be displayed if query returns 0 rows
  74.     $goto = 'tbl_properties_structure.php';
  75. } else {
  76.     // Now we can check the parameters
  77.     PMA_checkParameters(array('sql_query'));
  78. }
  79.  
  80. // instead of doing the test twice
  81. $is_drop_database = preg_match('/DROP[[:space:]]+(DATABASE|SCHEMA)[[:space:]]+/i',
  82.     $sql_query);
  83.  
  84. /**
  85.  * Check rights in case of DROP DATABASE
  86.  *
  87.  * This test may be bypassed if $is_js_confirmed = 1 (already checked with js)
  88.  * but since a malicious user may pass this variable by url/form, we don't take
  89.  * into account this case.
  90.  */
  91. if (!defined('PMA_CHK_DROP')
  92.     && !$cfg['AllowUserDropDatabase']
  93.     && $is_drop_database
  94.     && !$is_superuser) {
  95.     require_once './libraries/header.inc.php';
  96.     PMA_mysqlDie($strNoDropDatabases, '', '', $err_url);
  97. } // end if
  98.  
  99.  
  100. /**
  101.  * Need to find the real end of rows?
  102.  */
  103.  
  104. if (isset($find_real_end) && $find_real_end) {
  105.     $unlim_num_rows = PMA_Table::countRecords($db, $table, true, true);
  106.     $pos = @((ceil($unlim_num_rows / $session_max_rows) - 1) * $session_max_rows);
  107. }
  108. /**
  109.  * Avoids undefined variables
  110.  */
  111. elseif (!isset($pos)) {
  112.     $pos = 0;
  113. } else {
  114.     /* We need this to be a integer */
  115.     $pos = (int)$pos;
  116. }
  117.  
  118. /**
  119.  * Bookmark add
  120.  */
  121. if (isset($store_bkm)) {
  122.     PMA_addBookmarks($fields, $cfg['Bookmark'], (isset($bkm_all_users) && $bkm_all_users == 'true' ? true : false));
  123.     PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . $goto);
  124. } // end if
  125.  
  126.  
  127. /**
  128.  * Gets the true sql query
  129.  */
  130. // $sql_query has been urlencoded in the confirmation form for drop/delete
  131. // queries or in the navigation bar for browsing among records
  132. if (isset($btnDrop) || isset($navig)) {
  133.     $sql_query = urldecode($sql_query);
  134. }
  135.  
  136. /**
  137.  * Reformat the query
  138.  */
  139.  
  140. $GLOBALS['unparsed_sql'] = $sql_query;
  141. $parsed_sql = PMA_SQP_parse($sql_query);
  142. $analyzed_sql = PMA_SQP_analyze($parsed_sql);
  143.  
  144. // Bug #641765 - Robbat2 - 12 January 2003, 10:49PM
  145. // Reverted - Robbat2 - 13 January 2003, 2:40PM
  146.  
  147. // lem9: for bug 780516: now that we use case insensitive preg_match
  148. // or flags from the analyser, do not put back the reformatted query
  149. // into $sql_query, to make this kind of query work without
  150. // capitalizing keywords:
  151. //
  152. // CREATE TABLE SG_Persons (
  153. //  id int(10) unsigned NOT NULL auto_increment,
  154. //  first varchar(64) NOT NULL default '',
  155. //  PRIMARY KEY  (`id`)
  156. // )
  157. //
  158. // Note: now we probably do not need to fill and use $GLOBALS['unparsed_sql']
  159. // but I let this intact for now.
  160. //
  161. //$sql_query = PMA_SQP_formatHtml($parsed_sql, 'query_only');
  162.  
  163.  
  164. // check for a real SELECT ... FROM
  165. $is_select = isset($analyzed_sql[0]['queryflags']['select_from']);
  166.  
  167. // If the query is a Select, extract the db and table names and modify
  168. // $db and $table, to have correct page headers, links and left frame.
  169. // db and table name may be enclosed with backquotes, db is optionnal,
  170. // query may contain aliases.
  171.  
  172. // (TODO: if there are more than one table name in the Select:
  173. // - do not extract the first table name
  174. // - do not show a table name in the page header
  175. // - do not display the sub-pages links)
  176.  
  177. if ($is_select) {
  178.     $prev_db = $db;
  179.     if (isset($analyzed_sql[0]['table_ref'][0]['table_true_name'])) {
  180.         $table = $analyzed_sql[0]['table_ref'][0]['table_true_name'];
  181.     }
  182.     if (isset($analyzed_sql[0]['table_ref'][0]['db'])
  183.       && strlen($analyzed_sql[0]['table_ref'][0]['db'])) {
  184.         $db    = $analyzed_sql[0]['table_ref'][0]['db'];
  185.     } else {
  186.         $db = $prev_db;
  187.     }
  188.     // Nijel: don't change reload, if we already decided to reload in import
  189.     if (empty($reload)) {
  190.         $reload  = ($db == $prev_db) ? 0 : 1;
  191.     }
  192. }
  193.  
  194. /**
  195.  * Sets or modifies the $goto variable if required
  196.  */
  197. if ($goto == 'sql.php') {
  198.     $is_gotofile = false;
  199.     $goto = 'sql.php?'
  200.           . PMA_generate_common_url($db, $table)
  201.           . '&pos=' . $pos
  202.           . '&sql_query=' . urlencode($sql_query);
  203. } // end if
  204.  
  205.  
  206. /**
  207.  * Go back to further page if table should not be dropped
  208.  */
  209. if (isset($btnDrop) && $btnDrop == $strNo) {
  210.     if (!empty($back)) {
  211.         $goto = $back;
  212.     }
  213.     if ($is_gotofile) {
  214.         if (strpos(' ' . $goto, 'db_details') == 1 && isset($table) && strlen($table)) {
  215.             unset($table);
  216.         }
  217.         $active_page = $goto;
  218.         require './' . PMA_securePath($goto);
  219.     } else {
  220.         PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto));
  221.     }
  222.     exit();
  223. } // end if
  224.  
  225.  
  226. /**
  227.  * Displays the confirm page if required
  228.  *
  229.  * This part of the script is bypassed if $is_js_confirmed = 1 (already checked
  230.  * with js) because possible security issue is not so important here: at most,
  231.  * the confirm message isn't displayed.
  232.  *
  233.  * Also bypassed if only showing php code.or validating a SQL query
  234.  */
  235. if (!$cfg['Confirm']
  236.     || (isset($is_js_confirmed) && $is_js_confirmed)
  237.     || isset($btnDrop)
  238.  
  239.     // if we are coming from a "Create PHP code" or a "Without PHP Code"
  240.     // dialog, we won't execute the query anyway, so don't confirm
  241.     //|| !empty($GLOBALS['show_as_php'])
  242.     || isset($GLOBALS['show_as_php'])
  243.  
  244.     || !empty($GLOBALS['validatequery'])) {
  245.     $do_confirm = false;
  246. } else {
  247.     $do_confirm = isset($analyzed_sql[0]['queryflags']['need_confirm']);
  248. }
  249.  
  250. if ($do_confirm) {
  251.     $stripped_sql_query = $sql_query;
  252.     require_once './libraries/header.inc.php';
  253.     if ($is_drop_database) {
  254.         echo '<h1 class="warning">' . $strDropDatabaseStrongWarning . '</h1>';
  255.     }
  256.     echo '<form action="sql.php" method="post">' . "\n"
  257.         .PMA_generate_common_hidden_inputs($db, (isset($table)?$table:''));
  258.     ?>
  259.     <input type="hidden" name="sql_query" value="<?php echo urlencode($sql_query); ?>" />
  260.     <input type="hidden" name="zero_rows" value="<?php echo isset($zero_rows) ? PMA_sanitize($zero_rows) : ''; ?>" />
  261.     <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
  262.     <input type="hidden" name="back" value="<?php echo isset($back) ? PMA_sanitize($back) : ''; ?>" />
  263.     <input type="hidden" name="reload" value="<?php echo isset($reload) ? PMA_sanitize($reload) : 0; ?>" />
  264.     <input type="hidden" name="purge" value="<?php echo isset($purge) ? PMA_sanitize($purge) : ''; ?>" />
  265.     <input type="hidden" name="cpurge" value="<?php echo isset($cpurge) ? PMA_sanitize($cpurge) : ''; ?>" />
  266.     <input type="hidden" name="purgekey" value="<?php echo isset($purgekey) ? PMA_sanitize($purgekey) : ''; ?>" />
  267.     <input type="hidden" name="show_query" value="<?php echo isset($show_query) ? PMA_sanitize($show_query) : ''; ?>" />
  268.     <?php
  269.     echo '<fieldset class="confirmation">' . "\n"
  270.         .'    <legend>' . $strDoYouReally . '</legend>'
  271.         .'    <tt>' . htmlspecialchars($stripped_sql_query) . '</tt>' . "\n"
  272.         .'</fieldset>' . "\n"
  273.         .'<fieldset class="tblFooters">' . "\n";
  274.     ?>
  275.     <input type="submit" name="btnDrop" value="<?php echo $strYes; ?>" id="buttonYes" />
  276.     <input type="submit" name="btnDrop" value="<?php echo $strNo; ?>" id="buttonNo" />
  277.     <?php
  278.     echo '</fieldset>' . "\n"
  279.        . '</form>' . "\n";
  280. } // end if $do_confirm
  281.  
  282.  
  283. /**
  284.  * Executes the query and displays results
  285.  */
  286. else {
  287.     if (!isset($sql_query)) {
  288.         $sql_query = '';
  289.     }
  290.     // Defines some variables
  291.     // A table has to be created or renamed -> left frame should be reloaded
  292.     // TODO: use the parser/analyzer
  293.  
  294.     if (empty($reload)
  295.         && preg_match('/^(CREATE|ALTER|DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
  296.         $reload           = 1;
  297.     }
  298.     // Gets the number of rows per page
  299.     if (empty($session_max_rows)) {
  300.         $session_max_rows = $cfg['MaxRows'];
  301.     } elseif ($session_max_rows != 'all') {
  302.         $cfg['MaxRows']   = $session_max_rows;
  303.     }
  304.     // Defines the display mode (horizontal/vertical) and header "frequency"
  305.     if (empty($disp_direction)) {
  306.         $disp_direction   = $cfg['DefaultDisplay'];
  307.     }
  308.     if (empty($repeat_cells)) {
  309.         $repeat_cells     = $cfg['RepeatCells'];
  310.     }
  311.  
  312.     // SK -- Patch: $is_group added for use in calculation of total number of
  313.     //              rows.
  314.     //              $is_count is changed for more correct "LIMIT" clause
  315.     //              appending in queries like
  316.     //                "SELECT COUNT(...) FROM ... GROUP BY ..."
  317.  
  318.     // TODO: detect all this with the parser, to avoid problems finding
  319.     // those strings in comments or backquoted identifiers
  320.  
  321.     $is_explain = $is_count = $is_export = $is_delete = $is_insert = $is_affected = $is_show = $is_maint = $is_analyse = $is_group = $is_func = $is_replace = false;
  322.     if ($is_select) { // see line 141
  323.         $is_group = preg_match('@(GROUP[[:space:]]+BY|HAVING|SELECT[[:space:]]+DISTINCT)[[:space:]]+@i', $sql_query);
  324.         $is_func =  !$is_group && (preg_match('@[[:space:]]+(SUM|AVG|STD|STDDEV|MIN|MAX|BIT_OR|BIT_AND)\s*\(@i', $sql_query));
  325.         $is_count = !$is_group && (preg_match('@^SELECT[[:space:]]+COUNT\((.*\.+)?.*\)@i', $sql_query));
  326.         $is_export   = (preg_match('@[[:space:]]+INTO[[:space:]]+OUTFILE[[:space:]]+@i', $sql_query));
  327.         $is_analyse  = (preg_match('@[[:space:]]+PROCEDURE[[:space:]]+ANALYSE@i', $sql_query));
  328.     } elseif (preg_match('@^EXPLAIN[[:space:]]+@i', $sql_query)) {
  329.         $is_explain  = true;
  330.     } elseif (preg_match('@^DELETE[[:space:]]+@i', $sql_query)) {
  331.         $is_delete   = true;
  332.         $is_affected = true;
  333.     } elseif (preg_match('@^(INSERT|LOAD[[:space:]]+DATA|REPLACE)[[:space:]]+@i', $sql_query)) {
  334.         $is_insert   = true;
  335.         $is_affected = true;
  336.         if (preg_match('@^(REPLACE)[[:space:]]+@i', $sql_query)) {
  337.             $is_replace = true;
  338.         }
  339.     } elseif (preg_match('@^UPDATE[[:space:]]+@i', $sql_query)) {
  340.         $is_affected = true;
  341.     } elseif (preg_match('@^SHOW[[:space:]]+@i', $sql_query)) {
  342.         $is_show     = true;
  343.     } elseif (preg_match('@^(CHECK|ANALYZE|REPAIR|OPTIMIZE)[[:space:]]+TABLE[[:space:]]+@i', $sql_query)) {
  344.         $is_maint    = true;
  345.     }
  346.  
  347.     // Do append a "LIMIT" clause?
  348.     if (isset($pos)
  349.         && (!$cfg['ShowAll'] || $session_max_rows != 'all')
  350.         && !($is_count || $is_export || $is_func || $is_analyse)
  351.         && isset($analyzed_sql[0]['queryflags']['select_from'])
  352.         && !isset($analyzed_sql[0]['queryflags']['offset'])
  353.         && !preg_match('@[[:space:]]LIMIT[[:space:]0-9,-]+(;)?$@i', $sql_query)) {
  354.         $sql_limit_to_append = " LIMIT $pos, ".$cfg['MaxRows'] . " ";
  355.  
  356.         $full_sql_query  = $analyzed_sql[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_sql[0]['section_after_limit'];
  357.         // FIXME: pretty printing of this modified query
  358.  
  359.         if (isset($display_query)) {
  360.             // if the analysis of the original query revealed that we found
  361.             // a section_after_limit, we now have to analyze $display_query
  362.             // to display it correctly
  363.  
  364.             if (!empty($analyzed_sql[0]['section_after_limit']) && trim($analyzed_sql[0]['section_after_limit']) != ';') {
  365.                 $analyzed_display_query = PMA_SQP_analyze(PMA_SQP_parse($display_query));
  366.                 $display_query  = $analyzed_display_query[0]['section_before_limit'] . "\n" . $sql_limit_to_append . $analyzed_display_query[0]['section_after_limit'];
  367.             }
  368.         }
  369.  
  370.     } else {
  371.         $full_sql_query      = $sql_query;
  372.     } // end if...else
  373.  
  374.     if (isset($db)) {
  375.         PMA_DBI_select_db($db);
  376.     }
  377.  
  378.     // If the query is a DELETE query with no WHERE clause, get the number of
  379.     // rows that will be deleted (mysql_affected_rows will always return 0 in
  380.     // this case)
  381.     // Note: testing shows that this no longer applies since MySQL 4.0.x
  382.  
  383.     if (PMA_MYSQL_INT_VERSION < 40000) {
  384.         if ($is_delete
  385.             && preg_match('@^DELETE([[:space:]].+)?(FROM[[:space:]](.+))$@i', $sql_query, $parts)
  386.             && !preg_match('@[[:space:]]WHERE[[:space:]]@i', $parts[3])) {
  387.             $cnt_all_result = @PMA_DBI_try_query('SELECT COUNT(*) as count ' .  $parts[2]);
  388.             if ($cnt_all_result) {
  389.                 list($num_rows) = PMA_DBI_fetch_row($cnt_all_result);
  390.                 PMA_DBI_free_result($cnt_all_result);
  391.             } else {
  392.                 $num_rows   = 0;
  393.             }
  394.         }
  395.     }
  396.  
  397.     //  E x e c u t e    t h e    q u e r y
  398.  
  399.     // Only if we didn't ask to see the php code (mikebeck)
  400.     if (isset($GLOBALS['show_as_php']) || !empty($GLOBALS['validatequery'])) {
  401.         unset($result);
  402.         $num_rows = 0;
  403.     } else {
  404.         // garvin: Measure query time.
  405.         // TODO-Item http://sourceforge.net/tracker/index.php?func=detail&aid=571934&group_id=23067&atid=377411
  406.         $querytime_before = array_sum(explode(' ', microtime()));
  407.  
  408.         $result   = @PMA_DBI_try_query($full_sql_query, null, PMA_DBI_QUERY_STORE);
  409.  
  410.         $querytime_after = array_sum(explode(' ', microtime()));
  411.  
  412.         $GLOBALS['querytime'] = $querytime_after - $querytime_before;
  413.  
  414.         // Displays an error message if required and stop parsing the script
  415.         if ($error        = PMA_DBI_getError()) {
  416.             require_once './libraries/header.inc.php';
  417.             $full_err_url = (preg_match('@^(db_details|tbl_properties)@', $err_url))
  418.                           ? $err_url . '&show_query=1&sql_query=' . urlencode($sql_query)
  419.                           : $err_url;
  420.             PMA_mysqlDie($error, $full_sql_query, '', $full_err_url);
  421.         }
  422.         unset($error);
  423.  
  424.         // Gets the number of rows affected/returned
  425.         // (This must be done immediately after the query because
  426.         // mysql_affected_rows() reports about the last query done)
  427.  
  428.         if (!$is_affected) {
  429.             $num_rows = ($result) ? @PMA_DBI_num_rows($result) : 0;
  430.         } elseif (!isset($num_rows)) {
  431.             $num_rows = @PMA_DBI_affected_rows();
  432.         }
  433.  
  434.         // Checks if the current database has changed
  435.         // This could happen if the user sends a query like "USE `database`;"
  436.         $res = PMA_DBI_query('SELECT DATABASE() AS \'db\';');
  437.         $row = PMA_DBI_fetch_row($res);
  438.         if (isset($db) && is_array($row) && isset($row[0]) && (strcasecmp($db, $row[0]) != 0)) {
  439.             $db     = $row[0];
  440.             $reload = 1;
  441.         }
  442.         @PMA_DBI_free_result($res);
  443.         unset($res, $row);
  444.  
  445.         // tmpfile remove after convert encoding appended by Y.Kawada
  446.         if (function_exists('PMA_kanji_file_conv')
  447.             && (isset($textfile) && file_exists($textfile))) {
  448.             unlink($textfile);
  449.         }
  450.  
  451.         // Counts the total number of rows for the same 'SELECT' query without the
  452.         // 'LIMIT' clause that may have been programatically added
  453.  
  454.         if (empty($sql_limit_to_append)) {
  455.             $unlim_num_rows         = $num_rows;
  456.             // if we did not append a limit, set this to get a correct
  457.             // "Showing rows..." message
  458.             $GLOBALS['session_max_rows'] = 'all';
  459.         } elseif ($is_select) {
  460.  
  461.                 //    c o u n t    q u e r y
  462.  
  463.                 // If we are "just browsing", there is only one table,
  464.                 // and no where clause (or just 'WHERE 1 '),
  465.                 // so we do a quick count (which uses MaxExactCount)
  466.                 // because SQL_CALC_FOUND_ROWS
  467.                 // is not quick on large InnoDB tables
  468.  
  469.                 // but do not count again if we did it previously
  470.                 // due to $find_real_end == true
  471.  
  472.                 if (!$is_group
  473.                  && !isset($analyzed_sql[0]['queryflags']['union'])
  474.                  && !isset($analyzed_sql[0]['table_ref'][1]['table_name'])
  475.                  && (empty($analyzed_sql[0]['where_clause'])
  476.                    || $analyzed_sql[0]['where_clause'] == '1 ')
  477.                  && !isset($find_real_end)
  478.                  ) {
  479.  
  480.                     // "j u s t   b r o w s i n g"
  481.                     $unlim_num_rows = PMA_Table::countRecords($db, $table, true);
  482.  
  483.                 } else { // n o t   " j u s t   b r o w s i n g "
  484.  
  485.                     if (PMA_MYSQL_INT_VERSION < 40000) {
  486.  
  487.                         // detect this case:
  488.                         // SELECT DISTINCT x AS foo, y AS bar FROM sometable
  489.  
  490.                         if (isset($analyzed_sql[0]['queryflags']['distinct'])) {
  491.                             $count_what = 'DISTINCT ';
  492.                             $first_expr = true;
  493.                             foreach ($analyzed_sql[0]['select_expr'] as $part) {
  494.                                 $count_what .= (!$first_expr ? ', ' : '') . $part['expr'];
  495.                                 $first_expr = false;
  496.                             }
  497.                          } else {
  498.                              $count_what = '*';
  499.                          }
  500.                         // this one does not apply to VIEWs
  501.                         $count_query = 'SELECT COUNT(' . $count_what . ') AS count';
  502.                     }
  503.  
  504.                     // add the remaining of select expression if there is
  505.                     // a GROUP BY or HAVING clause
  506.                     if (PMA_MYSQL_INT_VERSION < 40000
  507.                      && $count_what =='*'
  508.                      && (!empty($analyzed_sql[0]['group_by_clause'])
  509.                         || !empty($analyzed_sql[0]['having_clause']))) {
  510.                         $count_query .= ' ,' . $analyzed_sql[0]['select_expr_clause'];
  511.                     }
  512.  
  513.                     if (PMA_MYSQL_INT_VERSION >= 40000) {
  514.                          // add select expression after the SQL_CALC_FOUND_ROWS
  515.  
  516.                             // for UNION, just adding SQL_CALC_FOUND_ROWS
  517.                             // after the first SELECT works.
  518.  
  519.                             // take the left part, could be:
  520.                             // SELECT
  521.                             // (SELECT
  522.                             $count_query = PMA_SQP_formatHtml($parsed_sql, 'query_only', 0, $analyzed_sql[0]['position_of_first_select'] + 1);
  523.                             $count_query .= ' SQL_CALC_FOUND_ROWS ';
  524.                             // add everything that was after the first SELECT
  525.                             $count_query .= PMA_SQP_formatHtml($parsed_sql, 'query_only', $analyzed_sql[0]['position_of_first_select']+1);
  526.                             // ensure there is no semicolon at the end of the 
  527.                             // count query because we'll probably add
  528.                             // a LIMIT 1 clause after it
  529.                             $count_query = rtrim($count_query);
  530.                             $count_query = rtrim($count_query, ';');
  531.                     } else { // PMA_MYSQL_INT_VERSION < 40000
  532.  
  533.                         if (!empty($analyzed_sql[0]['from_clause'])) {
  534.                             $count_query .= ' FROM ' . $analyzed_sql[0]['from_clause'];
  535.                         }
  536.                         if (!empty($analyzed_sql[0]['where_clause'])) {
  537.                             $count_query .= ' WHERE ' . $analyzed_sql[0]['where_clause'];
  538.                         }
  539.                         if (!empty($analyzed_sql[0]['group_by_clause'])) {
  540.                             $count_query .= ' GROUP BY ' . $analyzed_sql[0]['group_by_clause'];
  541.                         }
  542.                         if (!empty($analyzed_sql[0]['having_clause'])) {
  543.                             $count_query .= ' HAVING ' . $analyzed_sql[0]['having_clause'];
  544.                         }
  545.                     } // end if
  546.  
  547.                     // if using SQL_CALC_FOUND_ROWS, add a LIMIT to avoid
  548.                     // long delays. Returned count will be complete anyway.
  549.                     // (but a LIMIT would disrupt results in an UNION)
  550.  
  551.                     if (PMA_MYSQL_INT_VERSION >= 40000
  552.                     && !isset($analyzed_sql[0]['queryflags']['union'])) {
  553.                         $count_query .= ' LIMIT 1';
  554.                     }
  555.  
  556.                     // run the count query
  557.  
  558.                     if (PMA_MYSQL_INT_VERSION < 40000) {
  559.                         if ($cnt_all_result = PMA_DBI_try_query($count_query)) {
  560.                             if ($is_group && $count_what == '*') {
  561.                                 $unlim_num_rows = @PMA_DBI_num_rows($cnt_all_result);
  562.                             } else {
  563.                                 $unlim_num_rows = PMA_DBI_fetch_assoc($cnt_all_result);
  564.                                 $unlim_num_rows = $unlim_num_rows['count'];
  565.                             }
  566.                             PMA_DBI_free_result($cnt_all_result);
  567.                         } else {
  568.                             if (PMA_DBI_getError()) {
  569.  
  570.                                 // there are some cases where the generated
  571.                                 // count_query (for MySQL 3) is wrong,
  572.                                 // so we get here.
  573.                                 //TODO: use a big unlimited query to get
  574.                                 // the correct number of rows (depending
  575.                                 // on a config variable?)
  576.                                 $unlim_num_rows = 0;
  577.                             }
  578.                         }
  579.                     } else {
  580.                         PMA_DBI_try_query($count_query);
  581.                         // if (mysql_error()) {
  582.                         // void.
  583.                         // I tried the case
  584.                         // (SELECT `User`, `Host`, `Db`, `Select_priv` FROM `db`)
  585.                         // UNION (SELECT `User`, `Host`, "%" AS "Db",
  586.                         // `Select_priv`
  587.                         // FROM `user`) ORDER BY `User`, `Host`, `Db`;
  588.                         // and although the generated count_query is wrong
  589.                         // the SELECT FOUND_ROWS() work! (maybe it gets the
  590.                         // count from the latest query that worked)
  591.                         //
  592.                         // another case where the count_query is wrong:
  593.                         // SELECT COUNT(*), f1 from t1 group by f1
  594.                         // and you click to sort on count(*)
  595.                         // }
  596.                         $cnt_all_result       = PMA_DBI_query('SELECT FOUND_ROWS() as count;');
  597.                         list($unlim_num_rows) = PMA_DBI_fetch_row($cnt_all_result);
  598.                         @PMA_DBI_free_result($cnt_all_result);
  599.                     }
  600.             } // end else "just browsing"
  601.  
  602.         } else { // not $is_select
  603.              $unlim_num_rows         = 0;
  604.         } // end rows total count
  605.  
  606.         // garvin: if a table or database gets dropped, check column comments.
  607.         if (isset($purge) && $purge == '1') {
  608.             require_once './libraries/relation_cleanup.lib.php';
  609.  
  610.             if (isset($table) && isset($db) && strlen($table) && strlen($db)) {
  611.                 PMA_relationsCleanupTable($db, $table);
  612.             } elseif (isset($db) && strlen($db)) {
  613.                 PMA_relationsCleanupDatabase($db);
  614.             } else {
  615.                 // garvin: VOID. No DB/Table gets deleted.
  616.             } // end if relation-stuff
  617.          } // end if ($purge)
  618.  
  619.         // garvin: If a column gets dropped, do relation magic.
  620.         if (isset($cpurge) && $cpurge == '1' && isset($purgekey)
  621.           && isset($db) && isset($table)
  622.           && strlen($db) && strlen($table) && !empty($purgekey)) {
  623.             require_once './libraries/relation_cleanup.lib.php';
  624.             PMA_relationsCleanupColumn($db, $table, $purgekey);
  625.  
  626.         } // end if column PMA_* purge
  627.     } // end else "didn't ask to see php code"
  628.  
  629.     // No rows returned -> move back to the calling page
  630.     if ($num_rows < 1 || $is_affected) {
  631.         if ($is_delete) {
  632.             $message = $strDeletedRows . ' ' . $num_rows;
  633.         } elseif ($is_insert) {
  634.             if ($is_replace) {
  635.                 /* For replace we get DELETED + INSERTED row count, so we have to call it affected */
  636.                 $message = $strAffectedRows . ' ' . $num_rows;
  637.             } else {
  638.                 $message = $strInsertedRows . ' ' . $num_rows;
  639.             }
  640.             $insert_id = PMA_DBI_insert_id();
  641.             if ($insert_id != 0) {
  642.                 // insert_id is id of FIRST record inserted in one insert, so if we inserted multiple rows, we had to increment this
  643.                 $message .= '[br]'.$strInsertedRowId . ' ' . ($insert_id + $num_rows - 1);
  644.             }
  645.         } elseif ($is_affected) {
  646.             $message = $strAffectedRows . ' ' . $num_rows;
  647.  
  648.             // Ok, here is an explanation for the !$is_select.
  649.             // The form generated by sql_query_form.lib.php
  650.             // and db_details.php has many submit buttons
  651.             // on the same form, and some confusion arises from the
  652.             // fact that $zero_rows is sent for every case.
  653.             // The $zero_rows containing $strSuccess and sent with
  654.             // the form should not have priority over
  655.             // errors like $strEmptyResultSet
  656.         } elseif (!empty($zero_rows) && !$is_select) {
  657.             $message = $zero_rows;
  658.         } elseif (!empty($GLOBALS['show_as_php'])) {
  659.             $message = $strPhp;
  660.         } elseif (!empty($GLOBALS['validatequery'])) {
  661.             $message = $strValidateSQL;
  662.         } else {
  663.             $message = $strEmptyResultSet;
  664.         }
  665.  
  666.         $message .= ' ' . (isset($GLOBALS['querytime']) ? '(' . sprintf($strQueryTime, $GLOBALS['querytime']) . ')' : '');
  667.  
  668.         if ($is_gotofile) {
  669.             $goto = PMA_securePath($goto);
  670.             // Checks for a valid target script
  671.             $is_db = $is_table = false;
  672.             include 'libraries/db_table_exists.lib.php';
  673.             if (strpos($goto, 'tbl_properties') === 0 && ! $is_table) {
  674.                 if (isset($table)) {
  675.                     unset($table);
  676.                 }
  677.                 $goto = 'db_details.php';
  678.             }
  679.             if (strpos($goto, 'db_details') === 0 && ! $is_db) {
  680.                 if (isset($db)) {
  681.                     unset($db);
  682.                 }
  683.                 $goto = 'main.php';
  684.             }
  685.             // Loads to target script
  686.             if (strpos($goto, 'db_details') === 0
  687.              || strpos($goto, 'tbl_properties') === 0) {
  688.                 $js_to_run = 'functions.js';
  689.             }
  690.             if ($goto != 'main.php') {
  691.                 require_once './libraries/header.inc.php';
  692.             }
  693.             $active_page = $goto;
  694.             require './' . $goto;
  695.         } else {
  696.             PMA_sendHeaderLocation($cfg['PmaAbsoluteUri'] . str_replace('&', '&', $goto) . '&message=' . urlencode($message));
  697.         } // end else
  698.         exit();
  699.     } // end no rows returned
  700.  
  701.     // At least one row is returned -> displays a table with results
  702.     else {
  703.         // Displays the headers
  704.         if (isset($show_query)) {
  705.             unset($show_query);
  706.         }
  707.         if (isset($printview) && $printview == '1') {
  708.             require_once './libraries/header_printview.inc.php';
  709.         } else {
  710.             $js_to_run = 'functions.js';
  711.             unset($message);
  712.             if (isset($table) && strlen($table)) {
  713.                 require './libraries/tbl_properties_common.php';
  714.                 $url_query .= '&goto=tbl_properties.php&back=tbl_properties.php';
  715.                 require './libraries/tbl_properties_table_info.inc.php';
  716.                 require './libraries/tbl_properties_links.inc.php';
  717.             } elseif (isset($db) && strlen($db)) {
  718.                 require './libraries/db_details_common.inc.php';
  719.                 require './libraries/db_details_db_info.inc.php';
  720.             } else {
  721.                 require './libraries/server_common.inc.php';
  722.                 require './libraries/server_links.inc.php';
  723.             }
  724.         }
  725.  
  726.         if (isset($db) && strlen($db)) {
  727.             require_once './libraries/relation.lib.php';
  728.             $cfgRelation = PMA_getRelationsParam();
  729.         }
  730.  
  731.         // Gets the list of fields properties
  732.         if (isset($result) && $result) {
  733.             $fields_meta = PMA_DBI_get_fields_meta($result);
  734.             $fields_cnt  = count($fields_meta);
  735.         }
  736.  
  737.         // Display previous update query (from tbl_replace)
  738.         if (isset($disp_query) && $cfg['ShowSQL'] == true) {
  739.             $tmp_sql_query = $GLOBALS['sql_query'];
  740.             $GLOBALS['sql_query'] = $disp_query;
  741.             PMA_showMessage($disp_message);
  742.             $GLOBALS['sql_query'] = $tmp_sql_query;
  743.         }
  744.  
  745.         // Displays the results in a table
  746.         require_once './libraries/display_tbl.lib.php';
  747.         if (empty($disp_mode)) {
  748.             // see the "PMA_setDisplayMode()" function in
  749.             // libraries/display_tbl.lib.php
  750.             $disp_mode = 'urdr111101';
  751.         }
  752.         if (!isset($dontlimitchars)) {
  753.             $dontlimitchars = 0;
  754.         }
  755.  
  756.         // hide edit and delete links for information_schema
  757.         if (PMA_MYSQL_INT_VERSION >= 50002 && isset($db) && $db == 'information_schema') {
  758.             $disp_mode = 'nnnn110111';
  759.         }
  760.  
  761.         PMA_displayTable($result, $disp_mode, $analyzed_sql);
  762.         PMA_DBI_free_result($result);
  763.  
  764.         // BEGIN INDEX CHECK See if indexes should be checked.
  765.         if (isset($query_type) && $query_type == 'check_tbl' && isset($selected) && is_array($selected)) {
  766.             foreach ($selected AS $idx => $tbl_name) {
  767.                 $indexes        = $indexes_info = $indexes_data = array();
  768.                 $tbl_ret_keys   = PMA_get_indexes(urldecode($tbl_name), $err_url_0);
  769.  
  770.                 PMA_extract_indexes($tbl_ret_keys, $indexes, $indexes_info, $indexes_data);
  771.  
  772.                 $idx_collection = PMA_show_indexes(urldecode($tbl_name), $indexes, $indexes_info, $indexes_data, false);
  773.                 $check          = PMA_check_indexes($idx_collection);
  774.                 if (!empty($check)) {
  775.                 ?>
  776. <table border="0" cellpadding="2" cellspacing="0">
  777.     <tr>
  778.         <td class="tblHeaders" colspan="7"><?php printf($strIndexWarningTable, urldecode($tbl_name)); ?></td>
  779.     </tr>
  780.     <?php echo $check; ?>
  781. </table>
  782.                 <?php
  783.                 }
  784.             }
  785.         } // End INDEX CHECK
  786.  
  787.         // Bookmark Support if required
  788.         if ($disp_mode[7] == '1'
  789.             && (isset($cfg['Bookmark']) && $cfg['Bookmark']['db'] && $cfg['Bookmark']['table'] && empty($id_bookmark))
  790.             && !empty($sql_query)) {
  791.             echo "\n";
  792.  
  793.             $goto = 'sql.php?'
  794.                   . PMA_generate_common_url($db, $table)
  795.                   . '&pos=' . $pos
  796.                   . '&session_max_rows=' . $session_max_rows
  797.                   . '&disp_direction=' . $disp_direction
  798.                   . '&repeat_cells=' . $repeat_cells
  799.                   . '&dontlimitchars=' . $dontlimitchars
  800.                   . '&sql_query=' . urlencode($sql_query)
  801.                   . '&id_bookmark=1';
  802.  
  803.             ?>
  804. <form action="sql.php" method="post" onsubmit="return emptyFormElements(this, 'fields[label]');">
  805. <?php echo PMA_generate_common_hidden_inputs(); ?>
  806. <input type="hidden" name="goto" value="<?php echo $goto; ?>" />
  807. <input type="hidden" name="fields[dbase]" value="<?php echo htmlspecialchars($db); ?>" />
  808. <input type="hidden" name="fields[user]" value="<?php echo $cfg['Bookmark']['user']; ?>" />
  809. <input type="hidden" name="fields[query]" value="<?php echo urlencode(isset($complete_query) ? $complete_query : $sql_query); ?>" />
  810. <fieldset>
  811.     <legend><?php
  812.      echo ($cfg['PropertiesIconic'] ? '<img class="icon" src="' . $pmaThemeImage . 'b_bookmark.png" width="16" height="16" alt="' . $strBookmarkThis . '" />' : '')
  813.         . $strBookmarkThis;
  814. ?>
  815.     </legend>
  816.  
  817.     <div class="formelement">
  818.         <label for="fields_label_"><?php echo $strBookmarkLabel; ?>:</label>
  819.         <input type="text" id="fields_label_" name="fields[label]" value="" />
  820.     </div>
  821.  
  822.     <div class="formelement">
  823.         <input type="checkbox" name="bkm_all_users" id="bkm_all_users" value="true" />
  824.         <label for="bkm_all_users"><?php echo $strBookmarkAllUsers; ?></label>
  825.     </div>
  826.  
  827.     <div class="clearfloat"></div>
  828. </fieldset>
  829. <fieldset class="tblFooters">
  830.     <input type="submit" name="store_bkm" value="<?php echo $strBookmarkThis; ?>" />
  831. </fieldset>
  832. </form>
  833.             <?php
  834.         } // end bookmark support
  835.  
  836.         // Do print the page if required
  837.         if (isset($printview) && $printview == '1') {
  838.             ?>
  839. <script type="text/javascript" language="javascript">
  840. //<![CDATA[
  841. // Do print the page
  842. window.onload = function()
  843. {
  844.     if (typeof(window.print) != 'undefined') {
  845.         window.print();
  846.     }
  847. }
  848. //]]>
  849. </script>
  850.             <?php
  851.         } // end print case
  852.     } // end rows returned
  853.  
  854. } // end executes the query
  855.  
  856. /**
  857.  * Displays the footer
  858.  */
  859. require_once './libraries/footer.inc.php';
  860. ?>
  861.